﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Drawing;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Threading;

namespace AutoBuyWinform
{
    class Operations
    {
        //Logs logs;
        CheckCodeForm checkCodeForm;
        LinkedList<Thread> threadContainer = new LinkedList<Thread>();

        public LinkedList<Thread> getThreadContainer()
        {
            return this.threadContainer;
        }

        //用于存储获取newCheckCode信息的类
        public struct CheckCode
        {
            public string J_checkCodeUrl { get; set; }
            public string isCheckCode { get; set; }
            public string encrypterString { get; set; }
            public string sid { get; set; }
            public string gmtCreate { get; set; }
            public string checkCodeIds { get; set; }
            public string checkCode { get; set; }
        }

        public Operations()
        {
            //this.logs = logs;
            checkCodeForm = new CheckCodeForm();
        }

        public CookieCollection InitCookieCollection(CookieCollection ccReturned)
        {
            ccReturned.Add(new Cookie("Hm_lpvt_89e7e2c61beefae75bd63883432c760a","1366552029"));
            //ccReturned.Add(new Cookie("Hm_lvt_89e7e2c61beefae75bd63883432c760a", "1366442351,1366470053,1366520315,1366539392"));
            ////show cookie
            //StringBuilder sb = new StringBuilder();
            //foreach (Cookie cookieValue in ccReturned)
            //{
            //    sb.AppendLine("Cookie: " + cookieValue.ToString());
            //}
            //MessageBox.Show(sb.ToString());
            return ccReturned;
        }

        //获取验证码
        public string GetVeriCode(string loginUrl, string captchaUrl, CookieContainer cc, out CookieCollection ccReturned)
        {
            //string page = operations.GetPage(loginUrl, GetCookieContainerCopy(cc), out ccReturned);
            string page = Util.GetPage(loginUrl, cc, out ccReturned);
            cc.Add(ccReturned);

            ////show cookie
            //StringBuilder sb = new StringBuilder();
            //foreach (Cookie cookieValue in ccReturned)
            //{
            //    sb.AppendLine("Cookie: " + cookieValue.ToString());
            //}
            //MessageBox.Show(sb.ToString());

            //MessageBox.Show(page);
            Bitmap image = new Bitmap(Util.GetCheckCodeImageStream(captchaUrl, cc, out ccReturned));
            cc.Add(ccReturned);
            checkCodeForm.checkCodePic.Image = image;
            checkCodeForm.ShowDialog();
            return checkCodeForm.txtCheckCode.Text;

        }

        //用于登录的方法
        public bool Login(string loginUrl, string userName, string password, string veriCode, CookieContainer ccEntered, out CookieCollection ccReturned)
        {
            HttpWebRequest request;
            HttpWebResponse response;


            request = (HttpWebRequest)HttpWebRequest.Create(loginUrl+"/account/api/login/");
            request.CookieContainer = new CookieContainer();

            string data = "username=" + userName + "&password=" + password + "&captcha=" + veriCode;

            byte[] postData = Encoding.UTF8.GetBytes(data);

            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;

            //request.Connection = "keep-alive";

            request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.ContentLength = postData.Length;
            request.Referer = loginUrl;
            //request.KeepAlive = true;
            var sp = request.ServicePoint;
            var prop = sp.GetType().GetProperty("HttpBehaviour", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            prop.SetValue(sp, (byte)0, null);

            request.Accept = "application/json, text/javascript, */*; q=0.01";

            //request.Headers.Add("Connection", "keep-alive");

            request.Headers.Add("Cache-Control", "max-age=0");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("Origin", loginUrl);
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");

            request.CookieContainer = ccEntered;

            Stream st = request.GetRequestStream();
            st.Write(postData, 0, postData.Length);
            st.Close();

            request.AllowAutoRedirect = false;

            response = (HttpWebResponse)request.GetResponse();
            ccReturned = response.Cookies;


            Stream st2 = response.GetResponseStream();

            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st2, CompressionMode.Decompress, true);
            }

            string htmlText;

            StreamReader stReader = new StreamReader(st2, Encoding.Default);
            htmlText = stReader.ReadToEnd();

            stReader.Close();
            st2.Close();

            response.Close();

            RespStatus rs = JsonConvert.DeserializeObject<RespStatus>(htmlText);

            if (rs.status == 1)
            {
                MessageBox.Show("登陆成功");
            }
            else
            {
                if (rs.status == 0)
                {
                    MessageBox.Show("用户名或密码错误");
                }
                else if (rs.status == -3)
                {
                    MessageBox.Show("验证码错误");
                }
                else
                {
                    MessageBox.Show(rs.message);
                }
                
            }

            return rs.status == 1 ? true : false;
        }

        

        

        //通过URL打开页面，目前没用
        public string ToUrl(string toUrl,CookieContainer cc)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            request = WebRequest.Create(toUrl) as HttpWebRequest;
            request.Method = "GET";
            request.KeepAlive = false;
            request.CookieContainer = cc;

            // 提交请求数据
            response = request.GetResponse() as HttpWebResponse;
            using (System.IO.Stream responseStream = response.GetResponseStream())
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                {
                    string srcString = reader.ReadToEnd(); // 接收返回的页面
                    return srcString;
                }
            }

        }

        //生成商品对象
        public Product GetProduct(string productPage)
        {
            int btnIdx = productPage.IndexOf("javascript:addToCart");
            if (btnIdx == -1)
            {
                MessageBox.Show("请确认商品购买页面URL是否正确，无法找到\"加入购物车\"按钮。");
                return null;
            }

            int startIdx = productPage.IndexOf("(", btnIdx);
            int endIdx = productPage.IndexOf(";", btnIdx);
            string paramStr = productPage.Substring(startIdx + 1, endIdx - startIdx - 2);

            string[] param = paramStr.Split(new string[]{", "}, StringSplitOptions.RemoveEmptyEntries);
            Product product = new Product();
            product.packId = Int64.Parse(param[0].Trim());
            product.weight = Double.Parse(param[1].Trim());
            product.price = param[2].Trim().Replace("'","");
            product.productTypeId = param[3].Trim().Replace("'","");
            product.prodTypeDesc = param[4].Trim().Replace("'","");
            product.providerCode = param[5].Trim().Replace("'","");

            product.yj[0] = Form1.yj1;
            product.yj[1] = Form1.yj2;
            product.yj[2] = Form1.yj3;

            return product;
        }

        //加入购物车
        public bool AddToCart(Product product, CookieContainer ccEntered)
        {

            LogForm logFrom = new LogForm(product, ccEntered);
            logFrom.Text = product.prodTypeDesc + " 日志窗口";
            logFrom.Visible = true;
            logFrom.start();

            //Thread t = new Thread(() =>
            //{
            //    bool success = false;
            //    PostGoodsToCart pc = new PostGoodsToCart(product, ccEntered);
            //    success = pc.doPost();
            //    if (!success)
            //    {
            //        MessageBox.Show("加入购物车失败");
            //        return;
            //    }

            //    success = pc.createOrder();
            //    if (!success)
            //    {
            //        MessageBox.Show("生成订单失败");
            //        return;
            //    }

            //    MessageBox.Show("抢购成功！");

            //    Application.Run();
            //});
            //t.SetApartmentState(ApartmentState.MTA);
            //t.Start();
            //threadContainer.AddLast(t);

            return false;
        }

        //测试加入购物车
        public bool PostToCart(Product product, CookieContainer cc, out CookieCollection ccReturned)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            bool success = false;
            string csrftoken = "";
            ccReturned = null;

            request = (HttpWebRequest)HttpWebRequest.Create(Form1.postToCartUrl);
            request.CookieContainer = new CookieContainer();

            string data = "provider_code=" + product.providerCode + "&packId=" + product.packId;

            byte[] postData = Encoding.UTF8.GetBytes(data);

            //赋值权限戳
            //show cookie
            //StringBuilder sb = new StringBuilder();
            foreach (Cookie cookieValue in cc.GetCookies(new Uri(Form1.webUrl)))
            {
                if ("csrftoken".Equals(cookieValue.Name))
                {
                    csrftoken = cookieValue.Value;
                }
                //sb.AppendLine("Cookie: " + cookieValue.ToString());
            }
            //MessageBox.Show(sb.ToString());

            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;

            //request.Connection = "keep-alive";

            request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.ContentLength = postData.Length;
            request.Referer = Form1.goodsUrl;
            request.Accept = "application/json, text/javascript, */*; q=0.01";

            request.KeepAlive = true;
            //request.Headers.Add("Connection", "keep-alive");

            request.Headers.Add("Origin", Form1.goodsUrl);
            request.Headers.Add("Cache-Control", "max-age=0");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("X-CSRFToken", csrftoken);

            request.CookieContainer = cc;


            Stream st = request.GetRequestStream();
            st.Write(postData, 0, postData.Length);
            st.Close();

            request.AllowAutoRedirect = false;

            response = (HttpWebResponse)request.GetResponse();


            Stream st2 = response.GetResponseStream();

            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st2, CompressionMode.Decompress, true);
            }

            string htmlText;

            StreamReader stReader = new StreamReader(st2, Encoding.Default);
            htmlText = stReader.ReadToEnd();

            stReader.Close();
            st2.Close();

            response.Close();

            RespStatus rs = JsonConvert.DeserializeObject<RespStatus>(htmlText);

            if (rs.status == 1)
            {
                // 添加成功
                success = true;
            }
            else
            {
                MessageBox.Show(rs.message);
            }
            //else if (rs.status == 0)
            //{
            //    // 业务失败
            //}
            //else if (rs.status == -2)
            //{
            //    // 需要重新登录
            //}
            //else if (rs.status == 2)
            //{
            //    // 该资源已在购物车
            //}
            //else if (rs.status == -20)
            //{
            //    //showMessageDialog('未到开盘时间.');
            //}
            //else
            //{
            //    // 其他错误
            //}

            return success;
        }

        
    }
}
